package org.ellisande.grid.tags;

import java.util.EnumSet;

import javax.servlet.jsp.JspWriter;

import org.ellisande.grid.tags.support.TagBuilder;
import org.ellisande.tld.annotations.Attribute;
import org.ellisande.tld.annotations.Description;

public class TextInputTag extends InputTag {

	private static final long serialVersionUID = -365704155071475295L;

	private static enum Type {
		TEXT("text", ""), SEARCH("text", "search-query"), PASSWORD(
				"password", ""), EMAIL("email", ""), URL("url", "");

		private String inputType;
		private String style;

		private Type(String inputType, String style) {
			this.inputType = inputType;
			this.style = style;
		}

		public String style() {
			return style;
		}

		public String type() {
			return inputType;
		}

		public boolean equals(String type) {
			return name().equalsIgnoreCase(type);
		}
	}

	@Attribute
	@Description("Regular expression (regex) that defines validation criteria for this input.")
	private String validationPattern = "";

	@Attribute
	@Description("Defines the type of this text input. Allowed values: text | search | url | password | email")
	private Type type = Type.TEXT;

	@Attribute
	@Description("Default text value of the field.")
	private String value = "";

	@Attribute
	@Description("Hint to display in the field.")
	private String hint = "";

	private TagBuilder input = createInputTagBuilder();
	private TagBuilder div = createTagBuilder("div");

	private static final String DIV_STYLE = "controls";

	@Override
	public void startTag() throws Exception {
		div.addStyle(DIV_STYLE);
		if (validationPattern != null && !validationPattern.isEmpty()) {
			input.addAttribute("pattern", validationPattern);
		}
		if (value != null && !value.isEmpty()) {
			input.addAttribute("value", value);
		}
		if (hint != null && !hint.isEmpty()) {
			input.addAttribute("placeholder", hint);
		}
		input.addAttribute("type", type.type());
		input.addStyle(type.style());
		JspWriter out = pageContext.getOut();
		out.write(div.compileStartTag());
		out.write(input.compileStartTag());
	}

	@Override
	public void endTag() throws Exception {
		JspWriter out = pageContext.getOut();
		out.write(div.compileEndTag());
	}

	@Override
	public void release() {
		super.release();
		input = null;
		validationPattern = "";
		input = null;
		type = null;
		div = null;
	}

	public void setValidationPattern(String validationPattern) {
		this.validationPattern = validationPattern;
	}

	public void setType(String newType) {
		for (Type type : EnumSet.allOf(Type.class)) {
			if (type.equals(newType)) {
				this.type = type;
				return;
			}
		}

		this.type = Type.TEXT;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public void setHint(String hint) {
		this.hint = hint;
	}

}
